package com.yfqy.app.security;

import com.yfqy.app.security.exception.CustomAuthenticationExceptionHandler;
import com.yfqy.app.security.exception.CustomAuthorizationExceptionHandler;
import com.yfqy.app.security.exception.CustomSecurityExceptionHandler;
import com.yfqy.app.security.login.LoginFailHandler;
import com.yfqy.app.security.login.LoginSuccessHandler;
import com.yfqy.app.security.login.jscode.JSCodeAuthenticationFilter;
import com.yfqy.app.security.login.jscode.JSCodeAuthenticationProvider;
import com.yfqy.app.security.resourceapi.JwtAuthenticationFilter;
import com.yfqy.app.service.JwtService;
import jakarta.servlet.Filter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    private final ApplicationContext applicationContext;

    public SecurityConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private final AuthenticationEntryPoint authenticationExceptionHandler = new CustomAuthenticationExceptionHandler();
    private final AccessDeniedHandler authorizationExceptionHandler = new CustomAuthorizationExceptionHandler();
    private final Filter globalSpringSecurityExceptionHandler = new CustomSecurityExceptionHandler();

    private void commonConfig(HttpSecurity http) throws Exception {
        // 禁用SpringSecurity默认filter。这些filter都是非前后端分离项目的产物，用不上.
        // yml配置文件将日志设置DEBUG模式，就能看到加载了哪些filter
        // logging:
        //    level:
        //       org.springframework.security: DEBUG
        // 表单登录/登出、session管理、csrf防护等默认配置，如果不disable。会默认创建默认
        http
                .cors(AbstractHttpConfigurer::disable)
                .formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .sessionManagement(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                // requestCache用于重定向，前后端分析项目无需重定向，requestCache也用不上
                .requestCache(cache -> cache.requestCache(new NullRequestCache()))
                // 无需给用户一个匿名身份
                .anonymous(AbstractHttpConfigurer::disable);

        // 处理 SpringSecurity 异常响应结果。响应数据的结构，改成业务统一的JSON结构。不要框架默认的响应结构
        http.exceptionHandling(exceptionHandling ->
                exceptionHandling
                        .authenticationEntryPoint(authenticationExceptionHandler)
                        .accessDeniedHandler(authorizationExceptionHandler));

        // 其他未知异常. 尽量提前加载。SecurityContextHolderFilter 是属于springboot3.x.x版本的
        http.addFilterBefore(globalSpringSecurityExceptionHandler, SecurityContextHolderFilter.class);

    }

    @Bean("BCryptPasswordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 1. 公共API过滤器链 - 最高优先级
    @Bean
    @Order(1)
    public SecurityFilterChain publicApiFilterChain(HttpSecurity http) throws Exception {
        commonConfig(http);
        http.securityMatcher("/api/public/**")
                .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll());
        return http.build();
    }

    // 2. 登录过滤器链
    @Bean
    @Order(2)
    public SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
        commonConfig(http);
        http.securityMatcher("/api/user/login/*")
                .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated());

        LoginSuccessHandler loginSuccessHandler = applicationContext.getBean(LoginSuccessHandler.class);
        LoginFailHandler loginFailHandler = applicationContext.getBean(LoginFailHandler.class);

        // wx小程序jscode登录
        JSCodeAuthenticationFilter jsCodeLoginFilter = new JSCodeAuthenticationFilter(
                new AntPathRequestMatcher("/api/user/login/code2session", HttpMethod.POST.name()),
                new ProviderManager(applicationContext.getBean(JSCodeAuthenticationProvider.class)),
                loginSuccessHandler,
                loginFailHandler);
        http.addFilterBefore(jsCodeLoginFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 3. 受保护API过滤器链 - 最低优先级
    @Bean
    @Order(3)
    public SecurityFilterChain protectedApiFilterChain(HttpSecurity http) throws Exception {
        commonConfig(http);
        http.securityMatcher("/api/client/**")
                .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
                .addFilterBefore(new JwtAuthenticationFilter(
                        applicationContext.getBean(JwtService.class)
                ), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
    //@Bean
    //@Order(3)
    //public SecurityFilterChain protectedApiFilterChain(HttpSecurity http) throws Exception {
    //    commonConfig(http);
    //    http.securityMatcher("/api/internal/**", "/api/client/**")
    //            .authorizeHttpRequests(authorize -> authorize
    //                    .requestMatchers("/api/internal/**").hasAnyRole("ADMIN", "USER") // 后台管理系统角色
    //                    .requestMatchers("/api/client/**").hasAnyRole("CUSTOMER") // C端用户角色
    //                    .anyRequest().authenticated()
    //            )
    //            .addFilterBefore(new MyJwtAuthenticationFilter(
    //                    applicationContext.getBean(JwtService.class),
    //                    applicationContext.getBean(RedissonClient.class)
    //            ), UsernamePasswordAuthenticationFilter.class);
    //    return http.build();
    //}

    /**
     * 其余路径，走这个默认过滤链
     */
    @Bean
    @Order(value = Integer.MAX_VALUE) // 这个过滤链最后加载
    public SecurityFilterChain defaultApiFilterChain(HttpSecurity http) throws Exception {
        commonConfig(http);
        // 不用securityMatcher表示缺省值，匹配不上其他过滤链时，都走这个过滤链
        http
                .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated());
        http.addFilterBefore(new InvalidRequestFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    /**
     * 注意事项
     * 1.Spring Security优先：如果同时使用多种方式，Spring Security的CORS配置会优先于其他方式。
     * 2.CSRF保护：如果启用CSRF保护并允许跨域请求，需要确保正确处理CSRF令牌。
     * 3.Credentials：当设置allowCredentials(true)时，不能使用allowedOrigins("*")，必须指定具体域名。
     */

}